package com.healthtop.web.handler;

import com.healthtop.common.HttpUtils;
import com.healthtop.model.XsMenu;
import com.healthtop.service.*;
import com.healthtop.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by xiaoxiaobao on 2018/6/14.
 */
public class AuthenticationInterceptor implements HandlerInterceptor {


    @Autowired
    private XsUserService userService;

    @Autowired
    private XsMenuService xsMenuService;

    @Autowired
    private DIYService diyService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestUrl = request.getRequestURI();
        if(request.getSession().getAttribute("menus")!=null || requestUrl.contains("api")||requestUrl.contains("sites")){
            if (ObjectUtils.isEmpty(xsMenuService)) {
                xsMenuService = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()).getBean(XsMenuService.class);
            }
            String servletPath = request.getServletPath();
            XsMenu resource = xsMenuService.getMenuByPath(servletPath);
            if (resource != null) {
                request.getSession().setAttribute("node", resource);
            }
            if(requestUrl.contains("api")){
                if(!com.alibaba.druid.util.StringUtils.isEmpty(request.getParameter("userId"))) {
                    if(ObjectUtils.isEmpty(userService)){
                        userService = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()).getBean(XsUserService.class);
                    }
                }
            }
            if(requestUrl.contains("sites")){
                if(ObjectUtils.isEmpty(diyService)){
                    diyService = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()).getBean(DIYService.class);
                }
                //数据放session
                List<Map> cmsResources = diyService.getCmsXsMenuList();
                request.getSession().setAttribute("xsMenu",cmsResources);
            }
            return true;
        }

        response.sendRedirect("/sites/homePage");
        return false;
    }
}